package com.zero.demo.jms.web;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zero.demo.jms.entity.EncryptModel;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zengzr
 * @desc
 * @Date 2019/5/13 10:00
 */
public class FormHttpMessageConverter implements HttpMessageConverter<MultiValueMap<String, ?>> {


    private final List<MediaType> mediaTypes;
    private final ObjectMapper objectMapper;

    public FormHttpMessageConverter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
        this.mediaTypes = new ArrayList<>(1);
        this.mediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
    }

    @Override
    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        return true;
    }

    @Override
    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        return true;
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return mediaTypes;
    }

    @Override
    public MultiValueMap<String, ?> read(Class<? extends MultiValueMap<String, ?>> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
        String content = StreamUtils.copyToString(inputMessage.getBody(), Charset.forName("UTF-8"));
        EncryptModel in = objectMapper.readValue(content, EncryptModel.class);
        return objectMapper.readValue(in.getBody(),clazz);
    }

    @Override
    public void write(MultiValueMap<String, ?> stringMultiValueMap, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {

    }
}
